import random
import time

from proxmoxer import ProxmoxAPI

from ability.models import Instance

PROXMOX_HOST = '10.56.5.143'
PROXMOX_USER = 'root@pam'
PROXMOX_PASSWORD = 'CUC.2024.AXTX.dev'
NODE='pve'
# proxmox = ProxmoxAPI(host=PROXMOX_HOST, user=PROXMOX_USER, password=PROXMOX_PASSWORD, verify_ssl=False)
proxmox = None
def proxmox_connect():

  return  proxmox

def create_vm(template_id):
  # 指定节点和模板ID
  # 新虚拟机的配置参数
  # 根据模板id创建虚拟机
  new_vmid = None  # 确保这个 ID 是唯一的
  # 查询当前已存在的vmid
  vm_list = proxmox.nodes(NODE).qemu().get()
  vmids = [vm['vmid'] for vm in vm_list]
  while True:
    number = random.randint(100, 999999999)
    if number not in vmids:
      new_vmid = number
      break
  instances = Instance.objects.filter(status='N')
  port_list =  [instance.port for instance in instances] if instances != None else []
  new_port = None
  while True:
    port_id = random.randint(0,1000)
    if port_id not in port_list:
      new_port = port_id
      break
  vm_name = str(template_id)+'-'+str(new_vmid)
  config_params = {
    'name': vm_name,
    'newid': new_vmid,  # 确保这个 ID 是唯一的
    'full': 1 # 创建一个全克隆
  }
  response = proxmox.nodes(NODE).qemu(template_id).post('clone', **config_params)
  print(response)
  wait_for_task_completion(NODE,response)
  set_config(new_vmid,new_port)
  # 创建结束

  return {
    "vmid":new_vmid,
    "port":new_port
  }


def start_vm(vmid):
  proxmox.nodes(NODE).qemu(vmid).status.post('start')

def shutdown_vm(vmid):
  proxmox.nodes(NODE).qemu(vmid).status.shutdown.post()

def delete_vm(vmid):
  try:
    # 删除虚拟机
    response = proxmox.nodes(NODE).qemu(vmid).delete()
    print(f"Virtual machine {vmid} has been deleted.")
  except Exception as e:
    print(f"An error occurred while deleting the virtual machine: {e}")

def status_vm(vmid):  #查看虚拟机状态
  resp=proxmox.nodes(NODE).qemu(vmid).status.current.get()
  print(vmid)
  print(resp)
  print("---------------------------")
  return resp

def set_config(vmid,port):

  config_param = {"args":"-vnc 0.0.0.0:"+str(port)}
  task_id = proxmox.nodes(NODE).qemu(vmid).post('config',**config_param)
  print(task_id)
  wait_for_task_completion(NODE,task_id)
  start_task_id = proxmox.nodes(NODE).qemu(vmid).status.post('start')
  wait_for_task_completion(NODE,start_task_id)


def wait_for_task_completion(node, task_id):
  while True:
    # 获取任务的状态
    task_status = proxmox.nodes(node).tasks(task_id).status.get()
    status = task_status['status']
    if status == 'stopped':
      print("Task stopped unexpectedly.")
      break
    elif status == 'running':
      print("Task is still running...")
      time.sleep(2)  # 每隔2秒检查一次状态
    elif status == 'failed':
      print("Task failed.")
      break
    elif status == 'success':
      print("Task completed successfully.")
      break
    else:
      print(f"Unknown task status: {status}")
      break

# 修改虚拟机配置以启用 VNC
# task_id = proxmox.nodes(NODE).qemu(vmid).config.post({"args": "-vnc 0.0.0.0:" + str(port)})
# print(f"Task ID: {task_id['data']}")

# 使用函数等待任务完成
# wait_for_task_completion(proxmox, NODE, task_id['data'])

#查询所有模板信息
  def get_template_list():
    template_list = proxmox.nodes(NODE).qemu.get()
    # 打印公共镜像信息
    template_list_info = []
    for template in template_list:
         if 'template' in template and template['template'] == 1:
           print(template)
           print("\n")
           vm_details=proxmox.nodes('pve').qemu(template['vmid']).config.get()
           print(vm_details)
           vm_current_status=proxmox.nodes('pve').qemu(template['vmid']).status.current.get()
           print(vm_current_status)
           #模板信息
           template_list_info.append()
    return template_list_info